import { useEffect, useMemo, useState } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
import { IReducerState, IRootReducerState } from '@/store/root-reducer';
import { Button, Popconfirm, Space, Table, Toast } from '@douyinfe/semi-ui';
import {
  IconDeleteStroked,
  IconEditStroked,
  IconKeyStroked,
} from '@douyinfe/semi-icons';
import { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { PaginationProps } from '@douyinfe/semi-ui/lib/es/pagination';
import { usePageContext } from '../context';
import TablePagination, {
  onPageParamsChange,
} from '@/widgets/table-pagination';
import { pageSizeOpts } from '../helper';
import BaseColumns from './columns';
import { deleteItem } from '@/redux/role/role-api';
import { useDispatch } from 'react-redux';
import { fetchItems } from '@/redux/role/role-actions';

const roleTable = () => {
  const PageContext = usePageContext();
  const dispatch = useDispatch<any>();
  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
      setQueryParams: PageContext.setQueryParams,
      addRecord: PageContext.addRecord,
      editRecord: PageContext.editRecord,
      delRecord: PageContext.delRecord,
      appRecord: PageContext.appRecord,
    };
  }, [PageContext]);

  const { role } = useSelector<IRootReducerState, any>(
    (state) => ({ role: state.role }),
    shallowEqual
  );
  const { entities, totalCount } = role;
  const columns: ColumnProps[] = useMemo(() => {
    return [
      ...BaseColumns,
      {
        title: '操作',
        dataIndex: 'action',
        render: (text, record, index) => {
          return (
            <Space>
              <Button
                icon={<IconEditStroked />}
                onClick={() => {
                  PageAction.editRecord(record[role.key]);
                }}
              ></Button>
              <Button
                icon={<IconKeyStroked />}
                onClick={() => {
                  PageAction.appRecord(record[role.key]);
                }}
              ></Button>
              {record?.status === 1 ? (
                <Popconfirm
                  title='删除角色'
                  content='确定删除该角色?'
                  onConfirm={() => {
                    dispatch(deleteItem(record[role.key])).then((res: any) => {
                      dispatch(fetchItems(PageAction.queryParams));
                    });
                  }}
                >
                  <span className='inline-block invisible group-hover/item:visible'>
                    <Button
                      icon={<IconDeleteStroked style={{ color: '#ef4444' }} />}
                      onClick={() => {
                        // PageAction.delRecord(record[application.key]);
                      }}
                    ></Button>
                  </span>
                </Popconfirm>
              ) : (
                <span className='inline-block invisible group-hover/item:visible'>
                  <Button
                    icon={<IconDeleteStroked style={{ color: '#ef4444' }} />}
                    onClick={() => {
                      Toast.warning({
                        content: '角色未关闭，不可删除',
                        showClose: false,
                        duration: 2,
                      });
                    }}
                  ></Button>
                </span>
              )}
            </Space>
          );
        },
        // // 此处从render的第四个形参中解构出 展开按钮、选择按钮、文本等内容
        // render: (text, record, index, { expandIcon, selection, indentText }) => {
        //   return <>111</>;
        // })
      },
    ];
  }, []);

  const paginationOptions = useMemo(
    () => ({
      total: totalCount,
      queryParams: PageAction.queryParams,
      pageSizeOpts,
    }),
    [PageAction, role]
  );

  const onRowEvent: any = useMemo(
    () => (record: any, index: number) => {
      return {
        className: 'group/item',
      };
    },
    []
  );

  return (
    <TablePagination paginationOpts={paginationOptions}>
      {(paginationOpts: PaginationProps) => (
        <Table
          size='small'
          columns={columns}
          dataSource={entities}
          onChange={(params: any) =>
            onPageParamsChange(params, PageAction.setQueryParams)
          }
          onRow={onRowEvent}
          pagination={paginationOpts}
        />
      )}
    </TablePagination>
  );
};

export default roleTable;
